<?php
$this->title='speaking';
/* @var $this yii\web\View */
use app\assets\AppAsset;
use yii\helpers\Html;
use yii\helpers\Url;
use \yii\helpers\HtmlPurifier;
$this->registerJSFile('@web/js/swfobject.js',['depends'=>['app\assets\AppAsset']]);
$this->registerJSFile('@web/js/recorder.js',['depends'=>['app\assets\AppAsset']]);
$this->registerJSFile('@web/js/speakrecord.js',['depends'=>['app\assets\AppAsset']]);
$this->registerJSFile('@web/js/savenote.js',['depends'=>['app\assets\AppAsset']]);
$this->registerCssFile('@web/css/note.css',['depends'=>['app\assets\AppAsset']]);
$session = \Yii::$app->session;
$session->open();
$session['form']=2;
?>
<form action="?r=speaking/<?=$action;?>" id="nextque" method="post">
    <input type="hidden" name="page" value="<?=$page;?>">
    <input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
    <input name="usercheck" type="hidden" value="">
    <input type="hidden" name="post_type" value="">
</form>
<div class="container">

    <div class="leadx row clearfix">

        <div class="col-xs-3 pull-left">
            <span>
                Part
                <?=$speak_content['question_number'];
                ?>
                speaking
                Passage
                <?=$page-1;?>
                of
                <?=$speak_content['hear_number'];?>
            </span>
        </div>
        <div class="col-xs-1 pull-left notebook">
            <a href="#"><span><i class="fa fa-pencil-square-o"></i> 笔记</span></a>
        </div>
        <div class="col-xs-1 pull-right">
            <span><i class="fa fa-clock-o"></i></span>
        </div>
    </div>
    <div class="speak-wrap">
        <div class="speak-info row">
            Question
            <?=$speak_content['question_number']?>
            of
            6
        </div>
        <div class="p-que"><p class="que"><?=$speak_content['topic_content_english'];?></p>
        </div>
        <hr>
        <?php
        if($speak_content['type']==3) {
            ?>
            <div class="mychart">
                <i class="fa fa-wpforms"></i>&nbsp;&nbsp;<span>我的结构图</span><span id="icon"><i
                        class="fa fa-arrow-down"></i></span>
            </div>
            <?php
        }
        ?>
        <div class="record">
            <div class="record-control clearfix">
                <div class="record-repeat pull-left">
                    <span id="stop-text" class="hidden">Stop</span>
                    <span id="listen-text">Listen</span>
                    <img src="<?=Url::to('@web/images/start.png');?>" id="listenimg" alt="listen" onclick="FWRecorder.playBack('audio');">
                    <img src="<?=Url::to('@web/images/17.png');?>" id="stopimg" alt="repeat" onclick="FWRecorder.stopRecording('audio');" class="hidden">
                    <!-- FWRecorder.playBack('audio2');FWRecorder.stopRecording('audio'); -->
                </div>
                <div class="record-play pull-left">
                    <span>Record</span>
                    <img src="<?=Url::to('@web/images/15.png');?>" alt="play" id="playimg" onclick="FWRecorder.record('audio', 'audio.wav');">
                </div>
                <div class="record-submit pull-left">
                    <span>Submit</span>
                    <span id="flashcontent">
                    <p>Your browser must have JavaScript enabled and the Adobe Flash Player installed.</p>
                    </span>
                </div>
            </div>
            <div class="count-down">
                ······<span id="recordtime">00:00</span>······
            </div>

            <form id="uploadForm" name="uploadForm" action="?r=upload/qiniu">
                <input name="authenticity_token" value="xxxxx" type="hidden">
                <input name="upload_file[parent_id]" value="1" type="hidden">
                <input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
                <input name="format" value="json" type="hidden">
            </form>
        </div>
    </div>
    <div class="updating hidden">
        <span><img src="<?=Url::to('@web/images/updating.gif');?>" alt="上传中..."></span>
    </div>
</div>
<div class="addnote">
    <div class="note-lead">
        <span id="note-word">笔记</span>
        <span class="close"><i class="fa fa-times"></i></span>
    </div>
    <div class="note-text">
        <div contenteditable="true" id="note-self"><?=HtmlPurifier::process($my_note['note']);?></div>
    </div>
    <form action="#" id="note-form">
        <button type="button" name="note-save" id="note-submit">Save and Close</button>
        <input type="hidden" name="saved-note" value="">
    </form>
</div>
<div class="chart">
    <div class="closeit">
        <span id="close"><i class="fa fa-times"></i></span>
    </div>
    <div class="chart-one">
        <?php
        $session=Yii::$app->session;
        $session->open();
        ?>
        <div class="totalviews"><span class="view-lead">总观点</span><span><?= $session['total_views4']; ?></span>
        </div>
        <div class="firstview"><span class="view-lead">第一方面</span><span><?= $session['first_view4']; ?></span>
        </div>
        <div class="secondview"><span class="view-lead">第二方面</span><span><?= $session['second_view4']; ?></span>
        </div>
    </div>
    <div class="chart-two">
        <div class="totalviews"><span class="view-lead">总观点</span><?= $session['total_views5']; ?><span>
        </div>
        <div class="firstview"><span class="view-lead">第一方面</span><span><?= $session['first_view5']; ?></span>
        </div>
        <div class="secondview"><span class="view-lead">第二方面</span><span><?= $session['second_view5']; ?></span>
        </div>
    </div>
</div>
</div>
<script>
    window.onload = function () {
        var $uploadStatus = $('#upload_status'),
            $showLevelButton = $('.show_level'),
            $hideLevelButton = $('.hide_level'),
            $level = $('.control_panel .level');

        var CLASS_CONTROLS = "control_panel";
        var CLASS_RECORDING = "recording";
        var CLASS_PLAYBACK_READY = "playback_ready";
        var CLASS_PLAYING = "playing";
        var CLASS_PLAYBACK_PAUSED = "playback_paused";

//  Embedding flash object ---------------------------------------------------------------------------------------------

        setUpFormOptions();
        var appWidth = 24;
        var appHeight = 24;
        var flashvars = {'event_handler': 'microphone_recorder_events','upload_image':'<?=Url::to('@web/images/upload.png');?>'};
        var params = {};
        var attributes = {'id': "recorderApp", 'name': "recorderApp"};
        swfobject.embedSWF("<?=Url::to('@web/swf/recorder.swf');?>", "flashcontent", appWidth, appHeight, "11.0.0", "", flashvars, params, attributes);

//  Handling FWR events ------------------------------------------------------------------------------------------------
        var recordtime=0;
        var saved=false;
        var recordTime='';
        window.fwr_event_handler = function fwr_event_handler() {
            $('#status').prepend("<div class=\"recorder-event\">" + arguments[0] + "</div>");
            var name, $controls;
            switch (arguments[0]) {
                case "ready":
                    var width = parseInt(arguments[1]);
                    var height = parseInt(arguments[2]);
                    FWRecorder.uploadFormId = "#uploadForm";
                    FWRecorder.uploadFieldName = "upload_file[filename]";
                    FWRecorder.connect("recorderApp", 0);
                    FWRecorder.recorderOriginalWidth = width;
                    FWRecorder.recorderOriginalHeight = height;
                    $('.save_button').css({'width': width, 'height': height});
                    break;

                case "no_microphone_found":
                    break;

                case "microphone_user_request":
                    recorderEl().addClass("floating");
                    FWRecorder.showPermissionWindow();
                    break;

                case "microphone_connected":
                    FWRecorder.isReady = true;
                    $uploadStatus.css({'color': '#000'});
                    break;

                case "permission_panel_closed":
                    FWRecorder.defaultSize();
                    recorderEl().removeClass("floating");
                    break;

                case "microphone_activity":
                    $('#activity_level').text(arguments[1]);
                    break;

                case "recording":
                    name = arguments[1];
                    $controls = controlsEl(name);
                    FWRecorder.hide();
                    setControlsClass($controls, CLASS_RECORDING);
                    recordtime=0;
                    $("#recordtime").text(changeTime(recordtime));
                    $("#playimg").attr("src","<?=Url::to('@web/images/15.gif');?>");
                    $("#listenimg").addClass("hidden");
                    $("#listen-text").addClass("hidden");
                    $("#stopimg").removeClass("hidden");
                    $("#stop-text").removeClass("hidden");
                    clearInterval(recordTime);
                    recordTime=setInterval(function(){
                        if (recordtime>=59) {
                            $("#stopimg").click();
                        }
                        recordtime++;
                        $("#recordtime").text(changeTime(recordtime));
                    },1000)
                    break;

                case "recording_stopped":
                    name = arguments[1];
                    $controls = controlsEl(name);
                    var duration = arguments[2];
                    FWRecorder.show();
                    setControlsClass($controls, CLASS_PLAYBACK_READY);
                    $('#duration').text(duration.toFixed(4) + " seconds");
                    break;

                case "microphone_level":
                    $level.css({width: arguments[1] * 50 + '%'});
                    break;

                case "observing_level":
                    $showLevelButton.hide();
                    $hideLevelButton.show();
                    break;

                case "observing_level_stopped":
                    $showLevelButton.show();
                    $hideLevelButton.hide();
                    $level.css({width: 0});
                    break;

                case "playing":
                    name = arguments[1];
                    $controls = controlsEl(name);
                    setControlsClass($controls, CLASS_PLAYING);
                    break;

                case "playback_started":
                    name = arguments[1];
                    var latency = arguments[2];
                    break;

                case "stopped":
                    name = arguments[1];
                    $controls = controlsEl(name);
                    setControlsClass($controls, CLASS_PLAYBACK_READY);
                    break;

                case "playing_paused":
                    name = arguments[1];
                    $controls = controlsEl(name);
                    setControlsClass($controls, CLASS_PLAYBACK_PAUSED);
                    break;

                case "save_pressed":
                    FWRecorder.updateForm();
                    break;

                case "saving":
                    saved=false;
                    $(".updating").removeClass("hidden");
                    name = arguments[1];
                    break;

                case "saved":
                    saved=true;
                    $(".updating").addClass("hidden");
                    name = arguments[1];
                    var data = $.parseJSON(arguments[2]);
                    if (data.saved) {
                        $('#upload_status').css({'color': '#0F0'}).text(name + " was saved");
                    } else {
                        $('#upload_status').css({'color': '#F00'}).text(name + " was not saved");
                    }

                    break;

                case "save_failed":
                    name = arguments[1];
                    var errorMessage = arguments[2];
                    $uploadStatus.css({'color': '#F00'}).text(name + " failed: " + errorMessage);
                    break;

                case "save_progress":
                    saved=false;
                    name = arguments[1];
                    var bytesLoaded = arguments[2];
                    var bytesTotal = arguments[3];
                    $uploadStatus.css({'color': '#000'}).text(name + " progress: " + bytesLoaded + " / " + bytesTotal);
                    break;
            }
        };

//  Helper functions ---------------------------------------------------------------------------------------------------

        function setUpFormOptions() {
        }

        function setControlsClass($controls, className) {
            $controls.attr('class', CLASS_CONTROLS + ' ' + className);
        }

        function controlsEl(name) {
            return $('#recorder-' + name);
        }

        function recorderEl() {
            return $('#recorderApp');
        }


//  Button actions -----------------------------------------------------------------------------------------------------

        window.microphonePermission = function () {
            recorderEl().addClass("floating");
            FWRecorder.showPermissionWindow({permanent: true});
        };

        window.configureMicrophone = function () {
            if (!FWRecorder.isReady) {
                return;
            }
            FWRecorder.configure($('#rate').val(), $('#gain').val(), $('#silenceLevel').val(), $('#silenceTimeout').val());
            FWRecorder.setUseEchoSuppression($('#useEchoSuppression').is(":checked"));
            FWRecorder.setLoopBack($('#loopBack').is(":checked"));
        };



        $("#next").hover(function(){
            if (!saved) {
                $(this).css("cursor","not-allowed").find('a').css("cursor","not-allowed");
            }
        },function(){
            $(this).css("cursor","pointer").find('a').css("cursor","pointer");
        });
        $("#next").click(function(){
            if (!saved) {
                alert("请完成录制并上传");
                return false;
            }else{
                $("#nextque").submit();
            }
        })

        $(".record-repeat img").click(function(){
            clearInterval(recordTime);    
            $("#listenimg").removeClass("hidden");
            $("#listen-text").removeClass("hidden");
            $("#stopimg").addClass("hidden");
            $("#stop-text").addClass("hidden");
            $("#playimg").attr("src","<?=Url::to('@web/images/15.png');?>");
        })
        var $submit_time=$("[name=post_type]").clone(true).attr("name","time");
        $submit_time.appendTo("#nextque");
        var t=0;
        //计时
        $.ajax({
            url: "?r=ajax/gettime&state=<?=$state;?>&token=<?=$token;?>",
            dataType: 'json',
            type: 'get',
            success: function (data) {
                var $time=$("i.fa-clock-o");
                var sec=data.time;          //初始时间，以秒为单位
                setInterval(
                    function(){
                        sec++;
                        t++;
                        $time.html(secToMin(sec));
                        $submit_time.val(t);
                    },1000);
            }
        });
    };
</script>


